<?php

/**
 * 根据文件名获取云端存储bucket分类
 *
 * @param $file_name
 * @return int|string
 */
function get_oss_bucket_type($file_name) {
    $ext_arr = [
        'image' => ['gif','jpg','jpeg','png','bmp',],
        'audio' => ['mp3', 'wav', 'mid', 'ogg','ogv',],
        'media' => ['flv', 'swf', 'mkv', 'avi', 'rm', 'rmvb', 'mpeg', 'mpg','mov', 'wmv', 'mp4', 'webm', ],
        'file' => ['rar', 'zip', 'tar', 'gz', '7z', 'bz2', 'cab', 'iso','doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt', 'md', 'xml',]
    ];

    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $bucket_type = 'other';
    foreach ($ext_arr as $k => $arr) {
        if(in_array($file_ext, $arr)) {
            $bucket_type = $k;
            break;
        }
    }
    return $bucket_type;
}

/**
 * 产生随机数字字符串
 *
 * @param    int $length 输出长度
 * @param    string $chars 可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function random_num($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}


/**
 * 随机字符串
 *
 * @param int $len
 * @return string
 */
function str_rand($len = 6)
{
    $chars = 'abdefghijklmnopqrstuvwxyz0123456789';
    mt_srand((double)microtime() * 1000000 * getmypid());
    $str = '';
    while (strlen($str) < $len)
        $str .= substr($chars, (mt_rand() % strlen($chars)), 1);
    return $str;
}

/**
 * 获取完整URL
 *
 * @param $url
 * @return \Illuminate\Contracts\Routing\UrlGenerator|string
 */
function get_url($url)
{
    if (empty($url)) {
        return '';
    } else {
        return url($url);
    }
}

/**
 * 获取图片URL
 *
 * @param $url
 * @return string
 */
function get_image_url($url, $zoom = null)
{
    return get_cdn_url($url, 'image', $zoom);
}

/**
 * 获取视频URL
 *
 * @param $url
 * @return string
 */
function get_video_url($url)
{
    return get_cdn_url($url, 'video');
}

/**
 * 获取附件URL
 *
 * @param $url
 * @return string
 */
function get_other_url($url)
{
    return get_cdn_url($url, 'other');
}

function get_cdn_url($url, $type = 'image', $zoom = null)
{
    if (empty($url)) {
        return '';
    } elseif (!is_string($url) || strlen($url) < 5 || substr_compare(strtolower($url), 'http', 0, 4) == 0) {
        return $url;
    } else {
        return config('site.cdn.' . $type . '_url') . $url . ($zoom ? '_' . $zoom : '');
    }
}

function get_cdn_relative_url($url, $type = 'image'){
    if (empty($url)) {
        return '';
    } elseif (strpos($url,config('site.cdn.' . $type . '_url'))) {
        return substr($url,strlen(config('site.cdn.image_url')));
    } else {
        return $url;
    }
}

/**
 * 获取静态文件URL
 *
 * @param $url
 * @return string
 */
function get_static_url($url)
{
    return get_cdn_url($url, 'static');
}

/**
 * 替换编辑器内容中的相对图片URL为完整的cdn URL
 *
 * @param $content
 * @return mixed
 */
function replace_editor_image_url($content)
{
    return str_replace('"/uploads/images', '"' . config('site.cdn.image_url') . '/uploads/images', $content);
}

/**
 * 同步文件到七牛云
 *
 * @param $bucket
 * @param $relativeName
 * @param $sourceFile
 * @return bool
 */
function sync2qiniu($bucket, $relativeName, $sourceFile)
{
    $logString = Request::ip() . "\t" . implode("\t", func_get_args()) . "\t";
    $ret = true;

    if(Config::has('site.qiniu.enable') && config('site.qiniu.enable')){
        static $auth;

        if(!$auth){
            $AccessKey = config('site.qiniu.AccessKey');
            $SecretKey = config('site.qiniu.SecretKey');
            $auth = new \Qiniu\Auth($AccessKey, $SecretKey);
        }

        $uploadMgr = new \Qiniu\Storage\UploadManager();
        try{
            $token = $auth->uploadToken($bucket);
            if(substr($relativeName, 0 , 1) == '/'){
                $relativeName = substr($relativeName, 1);
            }
            list($ret, $err) = $uploadMgr->putFile($token, $relativeName, $sourceFile);
            if ($err !== null) {
                Log::error('qiniu_upload0', [
                    'msg'   =>  $err
                ]);
            } else {
                return true;
            }
        }catch (\Exception $e){
            Log::error('qiniu_upload1', [
                'msg'   =>  $e->getMessage()
            ]);
        }
    }else{
        Log::debug($logString . 'disable');
    }

    return $ret;
}

/**
 * 同步文件到阿里云
 *
 * @param $bucket
 * @param $relativeName
 * @param $sourceFile
 * @return bool
 */
function sync2oss($bucket, $relativeName, $sourceFile)
{
    $logString = Request::ip() . "\t" . implode("\t", func_get_args()) . "\t";
    $return = true;

    if(Config::has('site.oss.enable') && config('site.oss.enable')){
        static $ossClient;

        if(!$ossClient){
            $accessKeyId = config('site.oss.id');
            $accessKeySecret = config('site.oss.secret');
            $endpoint = config('site.oss.endpoint');
            try {
                $ossClient = new OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            } catch (OSS\Core\OssException $e) {
                $ossClient = null;
                Log::debug($logString . __FUNCTION__ . ": FAILED\t" . $e->getMessage());
                $return = false;
            }
        }

        $object = $relativeName;
        try{
            $bucketKey = 'site.oss.bucket.' . $bucket;
            if(Config::has($bucketKey)){
                $result = $ossClient->uploadFile(config($bucketKey), ltrim($object, '/'), $sourceFile);
                Log::debug($logString . "upload\t" . json_encode($result));
            }else{
                Log::debug($logString . 'bucket key: [' . $bucketKey . '] not found');
                $return = false;
            }
        } catch(OSS\Core\OssException $e) {
            Log::debug($logString . __FUNCTION__ . ": FAILED\t" . $e->getMessage());
            $return = false;
        }
    }else{
        Log::debug($logString . 'disable');
    }

    return $return;
}

/**
 * HTTP GET
 *
 * @param $url
 * @return string
 */
function curl_get($url)
{
    //初始化
    $ch = curl_init();

    //设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //执行并获取内容
    $result = curl_exec($ch);

    //释放curl句柄
    curl_close($ch);

    return $result;
}

/**
 * HTTP POST
 *
 * @param $url
 * @param $data
 * @return string
 */
function curl_post($url, $data)
{
    //初始化
    $ch = curl_init();

    //设置选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

    //执行并获取内容
    $result = curl_exec($ch);

    //释放curl句柄
    curl_close($ch);

    return $result;
}

function curl_post_json($url,$json)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json)
    ));
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

/**
 * 从缓存或回调函数中获取值（正式环境）
 * 从回调函数中获取值（开发环境）
 *
 * @param $key
 * @param $minutes
 * @param $callback
 * @return mixed
 */
function cache_remember($key, $minutes, $callback)
{
    if (env('APP_DEBUG')) {
        return call_user_func($callback);
    }
    else
    {
        return Cache::remember($key, $minutes, $callback);
    }
}

/**
 * 导出并下载excel文件
 *
 * @param $fileName
 * @param $rows
 * @return mixed
 */
function download_excel($fileName,  $rows) {
    //需要安装composer扩展包："maatwebsite/excel": "~2.1",
    return Excel::create($fileName, function($excel) use($rows) {
        $excel->sheet('Sheet1', function($sheet) use($rows) {
            $sheet->rows($rows);
        });
    })->download('xlsx');
}

function human_time($time, $format = 'Y-m-d H:i:s')
{
    if(is_string($time)){
        $time = strtotime($time);
    }else{
        $time = $time->getTimestamp();
    }

    $diff = \Carbon\Carbon::now()->getTimestamp() - $time;
    if($diff <= 600)
        return '刚刚';
    elseif($diff <= 3600)
        return floor($diff / 60) . '分钟前';
    elseif($diff <= 86400)
        return floor($diff / 3600) . '小时前';
    elseif($diff <= 864000)
        return floor($diff / 86400) . '天前';
    else
        return date($format, $time);
}

/**
 * 替换用户输入的标题
 * @param $title
 * @return string
 */
function replace_title($title)
{
    return strip_tags(preg_replace('/\s+/', '', $title));
}

/**
 * 替换用户输入的内容
 * @param $content
 * @return string
 */
function replace_content($content)
{
    return strip_tags(preg_replace('/(\r?\n){2,}/', "\r\n", trim($content)));
}

/**
 * 验证字段是否必填
 * $required 示例 [
'title' => '请输入标题',
'author' => '请输入作者',
'image_url' => '请上传封面图片',
'video_url|audio_url' => '必须上传[视频、音频]其中一种',
];
 *
 * @param $required
 * @return array
 */
function validate_fields($required) {
    $errors = [];
    foreach ($required as $key => $value) {
        $fields = explode('|',$key);
        if(count($fields) > 1) {
            $flag = false;
            foreach ($fields as $field) {
                if(! empty(Request::get($field))) {
                    $flag = true;
                }
            }
            if(! $flag) {
                $errors[] = $value;
            }
        } else {
            if(empty(Request::get($key))) {
                $errors[] = $value;
            }
        }
    }
    return $errors;
}

/**
 * 使用FFmpeg获取音视频播放总时长,码率，文件大小等信息
 *
 * @param $file
 * @return array
 */
function getMediaInfo($file) {
    $data = array();
    if(! file_exists($file)) {
        $file = public_path(ltrim($file, '/\\'));
        if(! file_exists($file)) {
            Log::debug('File is not found! file url:' . $file);
            return $data;
        }
    }
    $command = env('FFMPEG_PATH', '/usr/local/ffmpeg/ffmpeg') ." -i ${file} 2>&1";

    ob_start();
    passthru($command);
    $info = ob_get_contents();
    ob_end_clean();

    if (preg_match("/Duration: (.*?), start: (.*?), bitrate: (\d*) kb\/s/", $info, $match)) {
        $duration = $match[1];
        if($msIndex = strpos($duration, '.')) {
            $duration = substr($duration, 0, $msIndex);//时长只计算到秒,忽略掉毫秒
        }

        $data['duration'] = $duration; //播放时间
        $arr_duration = explode(':', $match[1]);
        $data['seconds'] = $arr_duration[0] * 3600 + $arr_duration[1] * 60 + $arr_duration[2]; //转换播放时间为秒数
        $data['seconds'] = intval($data['seconds']);//数值类型整形化
        $data['start'] = $match[2]; //开始时间
        $data['bitrate'] = $match[3]; //码率(kb)
    }
    if (preg_match("/Video: (.*?), (.*?), (.*?)[,\s]/", $info, $match)) {
        $data['vcodec'] = $match[1]; //视频编码格式
        $data['vformat'] = $match[2]; //视频格式
        $data['resolution'] = $match[3]; //视频分辨率
        $arr_resolution = explode('x', $match[3]);
        $data['width'] = empty($arr_resolution[0]) ? 0 :$arr_resolution[0];
        $data['height'] = empty($arr_resolution[1]) ? 0 :$arr_resolution[1];
    }
    if (preg_match("/Audio: (\w*), (\d*) Hz/", $info, $match)) {
        $data['acodec'] = $match[1]; //音频编码
        $data['asamplerate'] = $match[2]; //音频采样频率
    }
    if (isset($data['seconds']) && isset($data['start'])) {
        $data['play_time'] = $data['seconds'] + $data['start']; //实际播放时间
    }
    $data['size'] = filesize($file); //文件大小
    return $data;
}

/**
 * 验证中国大陆手机号是否正确
 *
 * @param $mobile
 * @return bool
 */
function is_mobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match("/^1[34578]\d{9}$/", $mobile) ? true : false;
}

/**
 * 长文本内容截取
 *
 * @param $str
 * @param $length
 * @return string
 */
function sub_string($str, $length) {
    if(mb_strlen($str,'utf-8') > $length) {
        $str = mb_substr($str, 0, $length,'utf-8') . '...';
    }
    return $str;
}

/**
 *  关于app中相关点击量、围观量等数字超过一定值，服务端优化显示举例
    最多保留1位小数，直接截取，不四舍五入
    小于1万，原始值：1110, 优化后值：1110
    大于1万，原始值：11100 ，优化后值：1.1万+  ；原始值：12100 ，优化后值：1.2万+
    小于1亿，原始值：1111200, 优化后值：111.1万+；
    大于1亿，原始值：111120000, 优化后值：1.1亿+；
 *
 * @param $num
 * @return string
 */
function format_number($num) {
    $num = intval($num);
    if($num<10000) {
        $newNum = $num;
    } elseif($num>=10000 && $num<100000000) {
        $newNum = strval(floor($num*10/10000)/10) . '万+';
    } elseif($num >= 100000000) {
        $newNum = strval(floor($num*10/100000000)/10) . '亿+';
    }
    return $newNum;
}

/**
 * 去除字符串中所有的空格（包括半角和全角）
 *
 * @param $str
 * @return null|string|string[]
 */
function clear_space($str)
{
    return preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/","",$str);
}
